/*
 * @Author: Setsuna
 * @Email: setsuna.xyz@qq.com
 * @FilePath: \src\pages\QuotaManage\StockCheck\QuatoDetail\component\PicturesWall.tsx
 * @Date: 2021-07-09 11:25:54
 * @LastEditTime: 2022-05-25 16:25:48
 */
import React, { useState } from 'react'
import { message, Input, Upload, Icon } from 'antd'
import ossHttp from '@/utils/oss'
import { getOssFileKey } from '@/utils/methods'
// import UploadImgButton from '@/components/UploadImgButton'

let deleteFiles = []
const UploadButton = (
  <div>
    <Icon type="plus" />
    <div className="ant-upload-text">上传图片</div>
  </div>
);
export default function (props) {
  // onFinish是从父组件传递过来的方法，用于修改父组件中的值
  const { updateDeleteFiles, updateFiles, items = [], onFinish } = props;
  const annexFile1 = props.annexFile;
  // 父组件传递进来默认的文件
  const [annexFile, setAnnexFile] = useState(annexFile1)
  // 附件上传
  const annexFileUpload = (file) => {
    const isJPNPNG = file.type === 'image/jpeg' || file.type === 'image/png'
    if (!isJPNPNG) {
      message.error('只能上传.jpg和.png格式图片')
      return false
    }
    const { name: fileName, uid } = file;
    setAnnexFile([...annexFile,{
      uid,
      name: fileName,
      status: 'uploading',
      // key: uid
    }])
    ossHttp.put('settled-review/annex', file).then(res => {
      const { url } = res;
      const file = {
        uid,
        name: fileName,
        status: 'done',
        url,
        // key: uid
      }
      updateFiles([file])
      setAnnexFile([...annexFile, file])
      // 修改父组件中的url值
      onFinish(url);
    })
    return false
  }
  // 附件删除
  const annexFileRemove = (file) => {
    // 先临时保存所有的文件
    let tmpFileList = annexFile;
    const { url } = file
    const key = getOssFileKey(url)
    if (needDelete(key)) {
      deleteFiles = [...deleteFiles, key]
      ossHttp.deleteMulti(deleteFiles)
    }
    // 在tmpFileList中去除掉 url = url的file
    tmpFileList = tmpFileList.filter((item) => {
      return item.url !== url;
    })
    setAnnexFile([...tmpFileList])
    return true
  }
  // 判断是否需要删除oss上的文件
  const needDelete = (key) => {
    if (!deleteFiles.includes(key)) {
      return true
    }
    return false
  }
  return (
    <div>
      {/* 解决闪动 */}
      <div style={{height: '130px', overflow: 'hidden'}}>
        上传凭证：
        <Upload
          beforeUpload={annexFileUpload}
          listType="picture-card"
          fileList={annexFile}
          onRemove={annexFileRemove}
        >
          {(annexFile.length < 6) ? UploadButton : null}
        </Upload>
      </div>
    支持扩展名.jpg，.png
    </div>
  )
}

